package com.xk.timesignature.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xk.timesignature.dto.UserDetailDTO;
import com.xk.timesignature.exception.ServiceException;
import com.xk.timesignature.mapper.RoleMapper;
import com.xk.timesignature.mapper.UserAuthMapper;
import com.xk.timesignature.mapper.UserInfoMapper;
import com.xk.timesignature.pojo.UserAuth;
import com.xk.timesignature.pojo.UserInfo;
import com.xk.timesignature.util.IpUtils;
import eu.bitwalker.useragentutils.UserAgent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.List;
import java.util.Objects;

import static com.xk.timesignature.enums.ZoneEnum.SHANGHAI;

/**
 * 登录实现类
 *
 * @author 空白
 * @date 2022/01/07
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private UserAuthMapper userAuthMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //1.判断用户名不为空
        if (StringUtils.isBlank(username)) {
            throw new ServiceException("用户名不能为空！");
        }

        //2.根据username查询数据库(lambda的意思是查询select()中的字段，忽略eq()中的字段。)
        UserAuth userAuth = userAuthMapper.selectOne(new LambdaQueryWrapper<UserAuth>()
                .select(UserAuth::getId, UserAuth::getUserInfoId, UserAuth::getUsername, UserAuth::getPassword)
                .eq(UserAuth::getUsername, username));
        if (Objects.isNull(userAuth)) {
            throw new ServiceException("用户名不存在！");
        }

        //3.封装登录信息，返回用户对象
        return convertUserDetail(userAuth, request);
    }

    /**
     *
     * @param userAuth 用户账号信息
     * @param request 请求
     * @return 用户登录信息
     */
    public UserDetailDTO convertUserDetail(UserAuth userAuth, HttpServletRequest request) {
        //查询账号信息
        UserInfo userInfo = userInfoMapper.selectById(userAuth.getUserInfoId());

        //查询账号角色
        List<String> roleList = roleMapper.roleListByUserInfoId(userInfo.getId());

        // 获取设备信息
        String ipAddress = IpUtils.getIpAddress(request);
        String ipSource = IpUtils.getIpSource(ipAddress);
        UserAgent userAgent = IpUtils.getUserAgent(request);

        // 封装权限集合
        return UserDetailDTO.builder()
                .id(userAuth.getId())
                .userInfoId(userInfo.getId())
                .username(userAuth.getUsername())
                .password(userAuth.getPassword())
                .email(userInfo.getEmail())
                .roleList(roleList)
                .nickname(userInfo.getNickname())
                .avatar(userInfo.getAvatar())
                .intro(userInfo.getIntro())
                .webSite(userInfo.getWebSite())
                .ipAddress(ipAddress)
                .ipSource(ipSource)
                .isDisable(userInfo.getIsDisable())
                .browser(userAgent.getBrowser().getName())
                .os(userAgent.getOperatingSystem().getName())
                .lastLoginTime(LocalDateTime.now(ZoneId.of(SHANGHAI.getZone())))
                .build();
    }
}
